import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import userApi from '../api/user'

export function useAuth() {
    const router = useRouter()
    const loginFormRef = ref()
    const registerFormRef = ref()
    const forgotPasswordFormRef = ref()

    // 状态控制
    const showRegister = ref(false)
    const showForgotPassword = ref(false)
    const loading = ref(false)
    const registerLoading = ref(false)
    const resetLoading = ref(false)
    const sendingCode = ref(false)
    const countdown = ref(0)
    let countdownTimer = null

    // 表单模型
    const loginForm = reactive({
        userType: 'enterprise',
        username: '',
        password: '',
        captcha: '',
    })

    const registerForm = reactive({
        companyName: '',
        companyContact: '',
        username: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        captcha: '',
        agreement: false,
    })

    const forgotPasswordForm = reactive({
        contact: '',
        verifyCode: '',
        newPassword: '',
        confirmNewPassword: '',
    })

    // 表单验证规则
    const loginRules = reactive({
        userType: [{ required: true, message: '请选择账号类型', trigger: 'change' }],
        username: [{ required: true, message: '请输入用户名或手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    })

    const validateConfirmPassword = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请再次输入密码'))
        } else if (value !== registerForm.password) {
            callback(new Error('两次输入的密码不一致'))
        } else {
            callback()
        }
    }

    const registerRules = reactive({
        companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        companyContact: [{ required: true, message: '请输入企业联系方式', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        agreement: [{ required: true, message: '请阅读并同意用户协议和隐私政策', trigger: 'change', transform: value => value || null }],
    })
    
    const forgotPasswordRules = reactive({
        contact: [{ required: true, message: '请输入注册时的手机号或邮箱', trigger: 'blur' }],
        verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        confirmNewPassword: [{ required: true, message: '请再次输入新密码', trigger: 'blur' }],
    })

    // 方法
    const refreshCaptcha = () => {
        //  TODO: 调用真实API刷新验证码
        console.log('Refreshing captcha...');
        ElMessage.success('验证码已刷新')
    }

    const startCountdown = () => {
        countdown.value = 60
        countdownTimer = setInterval(() => {
            if (countdown.value > 0) {
                countdown.value--
            } else {
                clearInterval(countdownTimer)
            }
        }, 1000)
    }

    onUnmounted(() => {
        if (countdownTimer) {
            clearInterval(countdownTimer)
        }
    })

    const sendVerifyCode = async () => {
        if (!forgotPasswordForm.contact) {
            ElMessage.warning('请输入手机号或邮箱');
            return;
        }
        sendingCode.value = true
        try {
            await userApi.sendVerificationCode({ contact: forgotPasswordForm.contact })
            ElMessage.success('验证码已发送，请注意查收')
            startCountdown()
        } catch (error) {
            ElMessage.error('验证码发送失败，请稍后重试')
        } finally {
            sendingCode.value = false
        }
    }

    const handleLogin = async () => {
        if (!loginFormRef.value) return
        await loginFormRef.value.validate(async (valid) => {
            if (valid) {
                loading.value = true
                try {
                    // TODO: 区分管理员和企业用户登录接口
                    const res = await userApi.login({
                        username: loginForm.username,
                        password: loginForm.password,
                    })
                    // 假设登录成功后后端返回 token 和用户信息
                    localStorage.setItem('token', res.token)
                    ElMessage.success('登录成功')
                    router.push('/dashboard/overview')
                } catch (error) {
                    ElMessage.error('登录失败，请检查用户名或密码')
                } finally {
                    loading.value = false
                }
            }
        })
    }
    
    const handleRegister = async () => {
        if (!registerFormRef.value) return
        await registerFormRef.value.validate(async (valid) => {
            if (valid) {
                registerLoading.value = true;
                try {
                    await userApi.register({
                        companyName: registerForm.companyName,
                        contact: registerForm.companyContact,
                        username: registerForm.username,
                        password: registerForm.password,
                        captcha: registerForm.captcha // 假设API需要这些字段
                    });
                    ElMessage.success('注册成功！');
                    showRegister.value = false; // 注册成功后返回登录页
                } catch (error) {
                    ElMessage.error('注册失败，请稍后重试');
                } finally {
                    registerLoading.value = false;
                }
            }
        });
    }

    const resetPassword = async () => {
        if (!forgotPasswordFormRef.value) return
        await forgotPasswordFormRef.value.validate(async (valid) => {
            if (valid) {
                if (forgotPasswordForm.newPassword !== forgotPasswordForm.confirmNewPassword) {
                    ElMessage.error('两次输入的新密码不一致');
                    return;
                }
                resetLoading.value = true
                try {
                    await userApi.resetPassword({
                        contact: forgotPasswordForm.contact,
                        verifyCode: forgotPasswordForm.verifyCode,
                        newPassword: forgotPasswordForm.newPassword,
                    })
                    ElMessage.success('密码重置成功')
                    showForgotPassword.value = false
                } catch (error) {
                    ElMessage.error('密码重置失败，请稍后重试')
                } finally {
                    resetLoading.value = false
                }
            }
        })
    }

    const switchToRegister = () => {
        showRegister.value = true;
    }

    const switchToLogin = () => {
        showRegister.value = false;
    }

    const openForgotPassword = () => {
        showForgotPassword.value = true;
    }

    const closeForgotPassword = () => {
        showForgotPassword.value = false;
    }


    return {
        // refs
        loginFormRef,
        registerFormRef,
        forgotPasswordFormRef,
        // state
        showRegister,
        showForgotPassword,
        loading,
        registerLoading,
        resetLoading,
        sendingCode,
        countdown,
        // forms
        loginForm,
        registerForm,
        forgotPasswordForm,
        // rules
        loginRules,
        registerRules,
        forgotPasswordRules,
        // methods
        handleLogin,
        handleRegister,
        resetPassword,
        refreshCaptcha,
        sendVerifyCode,
        switchToRegister,
        switchToLogin,
        openForgotPassword,
        closeForgotPassword
    }
} 